<?php


namespace app\common\command;


use app\common\cachemodel\ZlAstrExerciseRecord;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use XznsTools\cache\CacheManage;

class StarActivDataInsert extends Command
{
    /**
     * 命令配置
     */
    protected function configure()
    {
        $this->setName('star_activ:data_insert')->setDescription('占星师挑战缓存数据入库');
    }

    protected function execute(Input $input, Output $output)
    {
        print_r(date('Y-m-d H:i:s') . '占星师挑战缓存数据入库更新开始' . PHP_EOL);
        $redis = CacheManage::getInstance()->redisHandler;

        $keys = $redis->keys('astr_exercise:user_result:info:*');
        $totalNum = count($keys);
        print_r(date('Y-m-d H:i:s') . '需入库数据' . $totalNum . '条' . PHP_EOL);

        $i = 0;
        $model = new ZlAstrExerciseRecord();
        $insetNum = 0;
        $updateNum = 0;
        foreach ($keys as $cacheKey)
        {
            $userData = $redis->hGetAll($cacheKey);
            try
            {
                if (isset($userData['id']) && $userData['id'])
                {   // 更新
                    $model->where('id', (int)$userData['id'])->update([
                        'content2' => $userData['content2'],
                        'content3' => $userData['content3'],
                        'content4' => $userData['content4']
                    ]); // 更新
                    $updateNum++;
                } else
                {   // 入库
                    $id = $model->insertGetId($userData); // 入库
                    $redis->hMSet($cacheKey, ['id' => $id]);
                    $insetNum++;
                }

                $i++;
                if ($i % 100 === 0)
                {
                    print_r(date('Y-m-d H:i:s') . '已入库数据' . $i . '条;剩余' . ($totalNum - $i) . '条数据' . PHP_EOL);
                }
            }
            catch (\Exception $e)
            {
                print_r("数据异常；缓存Key【{$cacheKey}】;错误消息：" . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL);
            }
        }

        print_r(date('Y-m-d H:i:s') . "占星师挑战缓存数据入库更新完成;更新数据{$updateNum}条；写入数据{$insetNum}条；共处理数据{$i}条。" . PHP_EOL);
    }
}
